package com.ppt.android.base.utils

import kotlinx.coroutines.*

/**
 * 防抖
 *   当您调用debounce方法时，它将使用CoroutineScope和launch函数在500毫秒后运行传递的suspend函数。
 *   如果在500毫秒内再次调用debounce方法，则计时器将被重置，并且suspend函数将在500毫秒后再次运行。
 * @author ZouJiaCai
 * @since 2023/5/15 10:10
 */
object DebounceUtils {
    private val scope = CoroutineScope(Dispatchers.Default)
    private const val delay = 500L // 500 milliseconds

    private var job: Job? = null
    fun debounce(_delay: Long? = null,runnable: suspend () -> Unit) {
        job?.cancel()
        job = scope.launch {
            delay(_delay?: this@DebounceUtils.delay)
            runnable()
        }
    }
}